<template>
  <je-modal
    ref="$Ddlmodel"
    v-model:visible="visibleModule"
    :title="$t('viewModal.btnDdlText')"
    class="modal-comparison-ddl"
    :resize="false"
    :ok-button="addModule"
    cancel-button
    @close="cancelModal"
  >
    <je-row
      ref="$rowView"
      class="modal-comparison-ddl-row"
      type="flex"
      justify="space-between"
      style="height: 100%"
    >
      <je-col :span="12" style="height: 100%; padding-right: 10px">
        <je-collapse v-model:activeKey="activeKey" collapsible="disabled">
          <je-collapse-panel key="1" :show-arrow="false">
            <template #header>
              <div>
                输出列（原数据）：【<span class="line">{{ originalData.line }}</span
                >】条数据
              </div>
            </template>
            <div class="outputeditor-original" :style="`height: ${viewHeight.originalTopHeight}`">
              <je-editor-code
                key="originalEditor1"
                :value="originalData.outputColumn"
                language="sql"
                height="100%"
                width="100%"
                :editor-options="{ minimap: { enabled: false } }"
                :readonly="true"
              />
            </div>
          </je-collapse-panel>
          <je-collapse-panel key="2" :show-arrow="false">
            <template #header>
              <div class="condition">
                <div class="condition-tab">
                  <span
                    :class="[originalTabKey == 'originalTab1' ? 'checked' : '']"
                    @click.stop="doCutOriginalTab('originalTab1')"
                  >
                    关系条件（原数据）
                  </span>
                  <span
                    style="margin-left: 20px"
                    :class="[originalTabKey == 'originalTab2' ? 'checked' : '']"
                    @click.stop="doCutOriginalTab('originalTab2')"
                  >
                    关系说明
                  </span>
                </div>
                <div class="condition-button"
                  ><span class="btn" @click.stop="doCopyOriginalData">复制到新数据</span></div
                >
              </div>
            </template>
            <div :style="`height: ${viewHeight.originalBottomHeight}`">
              <je-editor-code
                v-if="originalTabKey == 'originalTab1'"
                key="originalEditor2"
                :value="originalData.condition"
                language="sql"
                height="100%"
                :editor-options="{ minimap: { enabled: false } }"
                width="100%"
                :readonly="true"
              />
              <div v-if="originalTabKey == 'originalTab2'" style="height: 100%">
                <je-textarea
                  v-model:value="originalData.conditionStatement"
                  disabled="false"
                  class="originalTab2-button-textarea"
                  style="height: 100%"
              /></div>
            </div>
          </je-collapse-panel>
        </je-collapse>
      </je-col>
      <je-col :span="12" style="height: 100%; padding-left: 10px">
        <je-collapse v-model:activeKey="activeKey" collapsible="disabled">
          <je-collapse-panel key="1" :show-arrow="false">
            <template #header>
              <div class="modify-output">
                <div>
                  输出列（新数据）：【<span class="line">{{ modifyData.line }}</span
                  >】条数据
                </div>
                <div class="modify-output-icon">
                  <span v-if="dataDetection.outputCloumn" style="color: red"
                    ><i style="margin-right: 5px" class="fal fa-warning"></i>数据有变化</span
                  >
                  <span v-if="!dataDetection.outputCloumn" style="color: green"
                    ><i class="fal fa-warning" style="margin-right: 5px"></i>数据无变化</span
                  >
                  <span
                    style="margin-left: 15px; cursor: pointer"
                    @click.stop="updateViewHeight('top')"
                    ><i
                      :class="`jeicon ${
                        updateHightMark.topMark == 'open' ? 'jeicon-an' : 'jeicon-packup'
                      }`"
                    ></i
                  ></span>
                </div>
              </div>
            </template>
            <div class="outputeditor-modify" :style="`height: ${viewHeight.modifyTopHeight}`">
              <je-editor-code
                key="modifyDataEditor1"
                v-model:value="modifyData.outputColumn"
                height="100%"
                language="sql"
                :hide-api="true"
                :editor-options="{ minimap: { enabled: false } }"
                width="100%"
              />
            </div>
          </je-collapse-panel>
          <je-collapse-panel key="2" :show-arrow="false">
            <template #header>
              <div class="condition">
                <div class="condition-tab">
                  <span
                    :class="[modifyTabKey == 'modifyTab1' ? 'checked' : '']"
                    @click.stop="doCutModifyTab('modifyTab1')"
                  >
                    关系条件（新数据）
                  </span>
                  <span
                    style="margin-left: 20px"
                    :class="[modifyTabKey == 'modifyTab2' ? 'checked' : '']"
                    @click.stop="doCutModifyTab('modifyTab2')"
                  >
                    关系说明
                  </span>
                </div>
                <div class="condition-button">
                  <span v-if="dataDetection.condition" style="color: red"
                    ><i style="margin-right: 5px" class="fal fa-warning"></i>数据有变化</span
                  >
                  <span v-if="!dataDetection.condition" style="color: green"
                    ><i class="fal fa-warning" style="margin-right: 5px"></i>数据无变化</span
                  >
                  <span
                    style="margin-left: 15px; cursor: pointer"
                    @click.stop="updateViewHeight('bottom')"
                    ><i
                      :class="`jeicon ${
                        updateHightMark.bottomMark == 'open' ? 'jeicon-an' : 'jeicon-packup'
                      }`"
                    ></i
                  ></span>
                </div>
              </div>
            </template>
            <div :style="`height: ${viewHeight.modifyBottomHeight}`">
              <je-editor-code
                v-if="modifyTabKey == 'modifyTab1'"
                key="modifyDataEditor2"
                v-model:value="modifyData.condition"
                language="sql"
                height="100%"
                :hide-api="true"
                :editor-options="{ minimap: { enabled: false } }"
                width="100%"
                @change="modifyConditionChange"
              />
              <div v-if="modifyTabKey == 'modifyTab2'" style="height: 100%; position: relative">
                <div class="modifyTab2-button">
                  <je-button type="text" @click="doTranslate">自然语言智能翻译</je-button>
                </div>
                <je-textarea
                  v-model:value="modifyData.conditionStatement"
                  class="modifyTab2-button-textarea"
                />
              </div>
            </div>
          </je-collapse-panel>
        </je-collapse>
      </je-col>
    </je-row>
  </je-modal>
</template>

<script>
  import { defineComponent, reactive, ref, nextTick, onMounted, watch } from 'vue';
  import { Modal, Row, Col, Collapse, EditorCode, Input, Button } from '@jecloud/ui';
  import { isNotEmpty } from '@jecloud/utils';
  import { getTranslate } from '@/api/index';
  export default defineComponent({
    name: 'ComparisonDdl',
    components: {
      JeModal: Modal,
      JeRow: Row,
      JeCol: Col,
      JeCollapse: Collapse,
      JeCollapsePanel: Collapse.Panel,
      JeEditorCode: EditorCode,
      JeTextarea: Input.TextArea,
      JeButton: Button,
    },
    props: {
      modalData: {
        type: String,
        required: true,
        default: '',
      },
      viewSql: {
        type: String,
        default: '',
      },
      oldTranslate: String,
      strData: String,
    },
    emits: ['changeDdlValue'],
    setup(props, { emit }) {
      const $rowView = ref(null);
      const visibleModule = ref(true);
      const activeKey = ref(['1', '2']);
      const originalTabKey = ref('originalTab1');
      const modifyTabKey = ref('modifyTab1');
      const viewHeight = reactive({
        originalTopHeight: '400px',
        originalBottomHeight: '200px',
        modifyTopHeight: '400px',
        modifyBottomHeight: '200px',
      });
      const updateHightMark = reactive({
        topMark: 'open',
        bottomMark: 'open',
      });
      // 数据变化监测
      const dataDetection = reactive({
        outputCloumn: false,
        condition: false,
      });
      const conditionFalg = ref(false);
      const $Ddlmodel = ref(null);

      // 初始化组件的高度
      const initViewHight = () => {
        if (isNotEmpty($rowView.value)) {
          const $el = $rowView.value.$el;
          const rowHight = $el.offsetHeight;
          const height = (rowHight - 35 * 2) / 2;
          viewHeight.originalTopHeight = height + 'px';
          viewHeight.originalBottomHeight = height + 'px';
          viewHeight.modifyTopHeight = height + 'px';
          viewHeight.modifyBottomHeight = height + 'px';
        }
      };

      watch(
        () => $rowView.value,
        () => {
          initViewHight();
        },
        { immediate: true },
      );

      onMounted(() => {
        nextTick(() => {
          initData();
          watch(
            () => $Ddlmodel.value?.reactData.zoomLocation,
            () => {
              doUpdateHight();
            },
          );
        });
      });

      // 原始数据
      const originalData = reactive({
        line: '',
        outputColumn: '',
        condition: '',
        conditionStatement: props.oldTranslate,
      });
      // 新数据
      const modifyData = reactive({
        line: '',
        outputColumn: '',
        condition: '',
        conditionStatement: props.oldTranslate,
      });

      const initData = () => {
        // 处理左侧原来的数据
        const oldSql = props.viewSql;
        const oldSqlArray = oldSql.split('FROM');
        originalData.outputColumn = oldSqlArray[0];
        originalData.condition = 'FROM' + oldSqlArray[1];
        originalData.line = originalData.outputColumn.split(',').length;
        // 处理右侧新的数据
        const newSql = props.modalData;
        const newSqlArray = newSql.split('FROM');
        modifyData.outputColumn = newSqlArray[0];
        modifyData.condition = 'FROM' + newSqlArray[1];
        modifyData.line = modifyData.outputColumn.split(',').length;
        // 对比数据是否有变动
        let outputColumn1 = originalData.outputColumn.replace('/n', '');
        let outputColumn2 = modifyData.outputColumn.replace('/n', '');
        dataDetection.outputCloumn = outputColumn1 != outputColumn2;
        let condition1 = originalData.condition.replace('/n', '');
        let condition2 = modifyData.condition.replace('/n', '');
        conditionFalg.value = dataDetection.condition = condition1 != condition2;
      };

      watch(
        () => modifyData.conditionStatement,
        () => {
          conditionFalg.value = false;
        },
      );

      // 点击确定按钮
      const addModule = ({ $modal }) => {
        if (conditionFalg.value) {
          Modal.confirm('关系条件发生变化，关系说明未进行调整，是否继续保存？', () => {
            emit(
              'changeDdlValue',
              modifyData.outputColumn + modifyData.condition,
              modifyData.conditionStatement,
            );
            $modal.close();
          });
        } else {
          emit(
            'changeDdlValue',
            modifyData.outputColumn + modifyData.condition,
            modifyData.conditionStatement,
          );
          $modal.close();
        }
        return false;
      };
      // 点击取消按钮
      const cancelModal = () => {
        visibleModule.value = false;
        emit('changeDdlValue', 'cancel');
      };
      // 复制到新数据
      const doCopyOriginalData = () => {
        modifyData.condition = originalData.condition;
        dataDetection.condition = false;
      };
      // 切换左侧tab签
      const doCutOriginalTab = (type) => {
        originalTabKey.value = type;
      };
      // 切换右侧侧tab签
      const doCutModifyTab = (type) => {
        modifyTabKey.value = type;
      };
      // 动态计算高度
      const updateViewHeight = (type) => {
        const $el = $rowView.value.$el;
        const rowHight = $el.offsetHeight;
        // 如果点的是上面要展开的按钮
        if (type == 'top' && updateHightMark.topMark == 'open') {
          const height = rowHight - 35 * 2 + 'px';
          viewHeight.originalTopHeight = height;
          viewHeight.modifyTopHeight = height;
          updateHightMark.topMark = 'off';
          updateHightMark.bottomMark = 'open';
          activeKey.value = ['1'];
        }
        // 如果点的是下面要展开的按钮
        else if (type == 'bottom' && updateHightMark.bottomMark == 'open') {
          const height = rowHight - 35 * 2 + 'px';
          viewHeight.originalBottomHeight = height;
          viewHeight.modifyBottomHeight = height;
          updateHightMark.bottomMark = 'off';
          updateHightMark.topMark = 'open';
          activeKey.value = ['2'];
        }
        // 恢复原始高度
        else if (updateHightMark.topMark == 'off' || updateHightMark.bottomMark == 'off') {
          const height = (rowHight - 35 * 2) / 2 + 'px';
          viewHeight.originalTopHeight = height;
          viewHeight.originalBottomHeight = height;
          viewHeight.modifyTopHeight = height;
          viewHeight.modifyBottomHeight = height;
          activeKey.value = ['1', '2'];
          if (type == 'top') {
            updateHightMark.topMark = 'open';
          } else {
            updateHightMark.bottomMark = 'open';
          }
        }
      };
      // 自然语言翻译
      const doTranslate = () => {
        getTranslate({ strData: props.strData, sql: modifyData.condition }).then((data) => {
          modifyData.conditionStatement = data;
        });
      };
      const modifyConditionChange = () => {
        conditionFalg.value = true;
      };
      const doUpdateHight = () => {
        const $el = $rowView.value.$el;
        const rowHight = $el.offsetHeight;
        if (updateHightMark.topMark == 'open' && updateHightMark.bottomMark == 'open') {
          const height = (rowHight - 35 * 2) / 2 + 'px';
          viewHeight.originalTopHeight = height;
          viewHeight.originalBottomHeight = height;
          viewHeight.modifyTopHeight = height;
          viewHeight.modifyBottomHeight = height;
        } else {
          const height = rowHight - 35 * 2 + 'px';
          if (updateHightMark.topMark == 'off') {
            viewHeight.originalTopHeight = height;
            viewHeight.modifyTopHeight = height;
          }
          if (updateHightMark.bottomMark == 'off') {
            viewHeight.originalBottomHeight = height;
            viewHeight.modifyBottomHeight = height;
          }
        }
      };
      return {
        visibleModule,
        cancelModal,
        addModule,
        activeKey,
        originalData,
        modifyData,
        originalTabKey,
        doCopyOriginalData,
        doCutOriginalTab,
        doCutModifyTab,
        modifyTabKey,
        $rowView,
        viewHeight,
        updateViewHeight,
        updateHightMark,
        dataDetection,
        doTranslate,
        modifyConditionChange,
        $Ddlmodel,
      };
    },
  });
</script>
<style lang="less" scoped>
  .modal-comparison-ddl {
    .modal-comparison-ddl-row {
      .line {
        color: #3265f5;
      }
      .condition {
        width: 100%;
        position: relative;
        .condition-button {
          position: absolute;
          right: 0;
          top: 0;
          span {
            display: inline-block;
          }
          .btn {
            color: #3265f5;
          }
        }
        .condition-tab {
          span {
            display: inline-block;
            cursor: pointer;
          }
          span.checked {
            position: relative;
            color: #3265f5;
            &::before {
              height: 2px;
              content: '';
              position: absolute;
              background: #3265f5;
              width: 100%;
              bottom: -1px;
            }
          }
        }
      }
      .modify-output {
        width: 100%;
        position: relative;
        .modify-output-icon {
          position: absolute;
          right: 0;
          top: 0;
        }
      }
      .modifyTab2-button {
        height: 32px;
        &-textarea {
          position: absolute;
          top: 32px;
          bottom: 0;
        }
      }
      .originalTab2-button-textarea {
        border: 0px;
      }
    }
  }
</style>
<style lang="less">
  .modal-comparison-ddl {
    .modal-comparison-ddl-row .ant-collapse {
      .ant-collapse-item {
        .ant-collapse-header {
          padding: 0px 16px !important;
          background: #f7f9fc !important;
          height: 32px;
          line-height: 32px;
          color: rgba(0, 0, 0, 0.85) !important;
          cursor: default !important;
        }
        .prompt {
          color: #3265f5;
          vertical-align: top;
          font-style: italic;
          margin-left: 10px;
        }
        .info {
          padding: 10px;
          border: 1px solid #a8d09d;
          background: #eff9f2;
          color: #36761f;
          font-size: 14px;
        }
        .ant-collapse-content {
          .ant-collapse-content-box {
            padding: 0 !important;
          }
        }
      }
    }
  }
</style>
